<?php
/**
 * Created by PhpStorm.
 * User: bzyy
 * Date: 2015年7月22日19:23:48
 */

class PostaltemplateModel extends BaseModel{

    const T_NUMBER = 1;//件数
    const T_WEIGHT = 2;//重量
    const T_VOLUME = 3;//体积

    public $table = 'postal_template';

    public $prikey = 'id';

    private $_exp_rules = array();
    private $_region_data = array();
    private $_region_link = array();



    public $_autov = array(
    'name' => array(
        'required'  => true,
        'filter'    => 'trim',

    ),
    'store_id' => array(
        'required'  => true,
        'filter'    => 'trim',
        'reg'   => '/\d+/'
    ),
    'code' => array(
        'required'  => true,
        'filter'    => 'trim',
        'reg'   => '/\d+/'
    ),
);

    /**
     * 对于重名的验证
     * @auth bzyy
     * 2015-7-22 20:09:04
     */
    public function unique($name,$store_id,$not_id=0){
        $cond = array();
        $cond['conditions'] = " name='{$name}' and store_id='{$store_id}' and id!='{$not_id}' ";
        $row = $this->get($cond);
        return empty($row);
    }

    /**
     * 编辑之前的处理
     * @auth bzyy
     * 2015-7-22 20:22:02
     */
    public function beforEdit(&$data,$user_id=0){
        $flag = true;
        if($user_id>0){
            //验证用户权限
        }

        //规划data有效性


        return $flag;
    }

    /*
     * 检测用户是否有某个店铺的访问权限
     * @auth bzyy
     * 2015-7-22 20:25:52
     */
    public function canedit($store_id,$user_id){
        return $store_id == $user_id;
    }

    /**
     * 添加的时候自动添加默认快递
     * @auth bzyy
     * 2015-7-24 18:36:38
     */
    public function add($data)
    {
        $flag = parent::add($data);
        if(!$flag)
        {
            return false;
        }

        //添加默认快递
        $default = array('postal_id'=>$flag,'name'=>'默认快递','is_default'=>1,'store_id'=>$data['store_id']);

        $model = m('postexpress');

        $f = $model->add($default);
        if(!$f){
            return false;
        }

        return $flag;

    }

    /**
     * 编辑
     * @auth bzyy
     * 2015-7-24 19:34:16
     */
    public function editinfo($id,$data,$addon)
    {

        $express = $data['express'];
        //保存当前数据
        //保存快递数据
        //var_dump($express);exit;

        //保存当前的信息
        $info = array('name'=>trim($data['name']));
        if(empty($info['name']))
        {
            $this->_error('模板名称不可以为空');
            return false;
        }

        $f = $this->unique($info['name'],$addon['store_id'],$id);
        if(!$f)
        {
            $this->_error('模板名称已存在，请另外指定');
            return false;
        }

        //补充信息

        $regioninfo = $this->regioninfo($data['region']);

        @list($country,$province,$city,$district) = $regioninfo['ids'];
        $info['country'] = intval($country);
        $info['province'] = intval($province);
        $info['city'] = intval($city);
        $info['district'] = intval($district);


        $flag = $this->edit($id,$info);
        if(!$flag)
        {
            return false;
        }


        $addon['postal_id'] = $id;

        $model = m('postexpress');



        $f = $model->editinfo($express,$addon);

        $this->_errors = $model->_errors;

        return $f;


    }


    /**
     * 取得详情信息
     * @auth bzyy
     * 2015-7-24 17:59:42
     */
    public function detail($id)
    {
        //取得所有的快递信息
        
        $model = m('postexpress');

        $data = $model->details($id);

        return $data;


    }


    /**
     * 取得地区信息
     * 并返回填充字段
     * @auth bzyy
     * 2015-7-30 13:36:11
     */
    public function regioninfo($id)
    {

        $ids = array();
        $names = array();
        do{
            $sql = "select region_id ,region_name,parent_id from ".$this->_prefix."region where region_id='{$id}'";

            $row = $this->getRow($sql);

            if(!empty($row))
            {
                $ids[] = $id;
                $names[] = $row['region_name'];
                $id = $row['parent_id'];
            }
        }while(!empty($row));

        $data = array();
        $data['ids'] = array_reverse($ids);
        $data['names'] = array_reverse($names);
        return $data;
    }


    /**
     * 删除的处理
     * @auth bzyy
     * 2015-7-30 15:56:33
     * //先删除子类在向上返调用
     */
    public function del($id)
    {
        $sql = "select id from ".$this->_prefix."post_express where postal_id='{$id}'";
        $temp_data = $this->getAll($sql);
        if(!empty($temp_data))
        {
            $express_ids = array();
            foreach($temp_data as $val)
            {
                $express_ids[] = $val['id'];
            }

            $model = m('postexpress');
            $f = $model->del($express_ids);
            if(!$f)
            {
                $this->_errors = $model->_errors;
                return false;
            }
        }
        $sql = "delete from ".$this->table." where id='{$id}' ";
        $f = $this->query($sql);
        if(!$f)
        {
            $this->_error('删除时发生错误');
            return false;
        }
        return true;

    }


    /**
     * @param $template_id
     *
     * 新方式找到对应的数据内容
     */
    public function detaildata($template_id)
    {
        $model = m('postexprule');
        $model_express = m('postexpress');
        $model_region = m('postruleregion');
        $model_reg = m('region');

        //load regions
        $this->_load_rules($template_id);

        //region info
        $this->_load_regions();

        //重组region数据
        foreach($this->_exp_rules as $key=>$val)
        {
            $this->_recombine($val);

            $this->_exp_rules[$key] = $val;
        }

        //添加对应的名称处理
//print_r($this->_exp_rules);exit;

        //加入对应的express
        $keys_express = array_keys($this->_exp_rules);
        $cond = array();
        $cond['conditions'] = "id in (".implode(',',$keys_express).")";
        $cond['order'] = "is_default desc";
        $data = $model_express->find($cond);

        foreach($data as $key=>$val)
        {
            $val['rules'] = $this->_exp_rules[$val['id']];

            $data[$key] = $val;
        }
//print_r($data);exit;
        return $data;




   }

    //查询用
    private function _load_rules($template_id)
    {
        $model = m('postexprule');
        $temp = $model->find("postal_id={$template_id}");
        $exp_data = array();
        foreach($temp as $val)
        {
            if($val['ctype'] == 0)
            {
                $exp_data[$val['express_id']]['com'][] = $val;
            }
            elseif($val['ctype'] == PostexpressModel::RULE_FREE)
            {
                $exp_data[$val['express_id']]['free'] = $val;
            }elseif($val['ctype'] == PostexpressModel::RULE_DEFAULT)
            {
                $exp_data[$val['express_id']]['def'] = $val;
            }
        }

        $this->_exp_rules = $exp_data;
    }

    //载入地区
    private function _load_regions()
    {
        $model = m('postexprule');
        $model_express = m('postexpress');
        $model_region = m('postruleregion');
        $model_reg = m('region');

        $express_ids = array_keys($this->_exp_rules);
        $express_ids[] = 0;

        $regions = $model_region->find("express_id in (". implode(',',$express_ids) .")");

        //找到对应的regions_ids
        $regions_ids = array();
        $temp_reg_data = array();
        foreach($regions as $val)
        {
            $regions_ids[] = $val['province'];
            $temp_reg_data[$val['express_id']][$val['rule_id']][$val['country']][] = $val['province'];
        }
        if(empty($regions_ids))
        {
            return ;
        }

        //根据这个地址load地区信息
        $temp = $model_reg->find("region_id in (". implode(',',$regions_ids) .")");
        $region_info = array();
        foreach($temp as $val)
        {
            $region_info[$val['region_id']] = $val;
        }

        $this->_region_link = $temp_reg_data;
        $this->_region_data = $region_info;
    }

    //
    private function _recombine(&$data)
    {
        //com
        if(isset($data['com']))
        {
            foreach($data['com'] as $key=>$val)
            {
                $temp_region = array();
                if(isset($this->_region_link[$val['express_id']][$val['id']]))
                {
                    $temp = $this->_region_link[$val['express_id']][$val['id']];
                    foreach($temp as $kk=>$vv)
                    {
                        $names = $this->_region_names($vv);
                        $temp_region[$kk] = array('val'=>implode(',',$vv),'name'=>implode('&nbsp;',$names));
                    }
                }
                $val['regions'] = $temp_region;
                $data['com'][$key] = $val;

            }

        }
        //free
        if(isset($data['free']))
        {
            $temp_region = array();
            if(isset($this->_region_link[$data['free']['express_id']][$data['free']['id']]))
            {
                $temp = $this->_region_link[$data['free']['express_id']][$data['free']['id']];
                foreach($temp as $kk=>$vv)
                {
                    $names = $this->_region_names($vv);
                    $temp_region[$kk] = array('val'=>implode(',',$vv),'name'=>implode('&nbsp;',$names));
                }
            }
            $data['free']['regions'] = $temp_region;
        }
        //def
        if(isset($data['def']))
        {
            $temp_region = array();
            if(isset($this->_region_link[$data['def']['express_id']][$data['def']['id']]))
            {
                $vv = $this->_region_link[$data['def']['express_id']][$data['def']['id']];
                $names = $this->_region_names($vv);
                $temp_region['val']=implode(',',$vv);
                $temp_region['name'] = implode('&nbsp;',$names);
            }
            $data['def']['regions'] = $temp_region;
        }
    }

    //组合地址名称
    private function _region_names($regions)
    {
        $names = array();
        foreach($regions as $v)
        {
            if(isset($this->_region_data[$v]))
            {
                $names[] = $this->_region_data[$v]['region_name'];
            }
        }
        return $names;

    }








} 